package com.aizhixin.lab.project.template.service;

import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.core.PublicErrorCode;
import com.aizhixin.lab.project.template.core.WorkOrderFileType;
import com.aizhixin.lab.project.template.domain.DeleteDomain;
import com.aizhixin.lab.project.template.domain.ProjectRoleDomain;
import com.aizhixin.lab.project.template.domain.WorkOrderDomain;
import com.aizhixin.lab.project.template.domain.WorkOrderFileDomain;
import com.aizhixin.lab.project.template.entity.*;
import com.aizhixin.lab.project.template.repository.ExercisesRepository;
import com.aizhixin.lab.project.template.repository.ModuleTaskRepository;
import com.aizhixin.lab.project.template.repository.TaskWorkOrderRepository;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
@Transactional
public class WorkOrderService {
    @Autowired
    private TaskWorkOrderRepository workOrderRepository;
    @Autowired
    private WorkOrderFileService fileService;
    @Autowired
    private ModuleTaskRepository taskRepository;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ExercisesRepository exercisesRepository;

    public void updateSort(List<String> ids){
        int i=1;
        for (String id : ids) {
            TaskWorkOrder taskWorkOrder = workOrderRepository.findByIdAndDeleteFlag(id, DataValidity.VALID.getState());
            taskWorkOrder.setWorkOrderNo(i);
            workOrderRepository.save(taskWorkOrder);
            i++;
        }
    }

    public String save(WorkOrderDomain domain) {
        Boolean isNew = false;
        if (null == domain.getId() || "".equals(domain.getId())) {
            domain.setId(UUID.randomUUID().toString());
            isNew = true;
        }
        List<WorkOrderFile> workOrderFileList = new ArrayList<>();
        List<ProjectRole> projectRoles = new ArrayList<>();
        for (ProjectRoleDomain roleDomain : domain.getProjectRoleDomainList()) {
            ProjectRole projectRole = new ProjectRole();
            BeanUtils.copyProperties(roleDomain, projectRole);
            projectRoles.add(projectRole);
        }
        if (domain.getSoundCode() != null) {
            workOrderFileList.addAll(copyToWorkOrderFile(domain.getSoundCode(), WorkOrderFileType.soundCode.getIntValue(), domain.getId()));
        }
        if (domain.getWorkOrderMaterial() != null) {
            workOrderFileList.addAll(copyToWorkOrderFile(domain.getWorkOrderMaterial(), WorkOrderFileType.material.getIntValue(), domain.getId()));
        }
        if (domain.getVideo() != null) {
            workOrderFileList.addAll(copyToWorkOrderFile(domain.getVideo(), WorkOrderFileType.video.getIntValue(), domain.getId()));
        }
        if (domain.getWorkStepList() != null) {
            workOrderFileList.addAll(copyToWorkOrderFile(domain.getWorkStepList(), WorkOrderFileType.workStep.getIntValue(), domain.getId()));
        }

        if (isNew) {
            TaskWorkOrder taskWorkOrder = new TaskWorkOrder();
            taskWorkOrder.setId(UUID.randomUUID().toString());
            taskWorkOrder.setCreatedDate(new Date());
            taskWorkOrder.setDeleteFlag(DataValidity.VALID.getState());
            taskWorkOrder.setProjectRoleList(projectRoles);
            Integer workOrderNum = countWorkOrder(domain.getTaskId());
            taskWorkOrder.setWorkOrderNo(workOrderNum+1);
            BeanUtils.copyProperties(domain, taskWorkOrder);
            ModuleTask moduleTask = taskRepository.findOne(domain.getTaskId());
            if (!Objects.isNull(moduleTask)) {
                moduleTask.setWorkOrderNum(moduleTask.getWorkOrderNum() + 1);
                taskRepository.save(moduleTask);
            }
            Project project = projectService.findProject(domain.getProjectId());
            if (!Objects.isNull(project)) {
                project.setWorkOrderNum(project.getWorkOrderNum() == null ? 0 : project.getWorkOrderNum() + 1);
                projectService.save(project);
            }
            workOrderRepository.save(taskWorkOrder);
            fileService.save(workOrderFileList);
            return domain.getId();
        }
        TaskWorkOrder one = workOrderRepository.findOne(domain.getId());
        BeanUtils.copyProperties(domain, one);
        one.setProjectRoleList(projectRoles);
        one.setDeleteFlag(DataValidity.VALID.getState());
        fileService.deleteByWorkOrderId(one.getId());
        fileService.save(workOrderFileList);
        workOrderRepository.save(one);
        return domain.getId();
    }

    public List<WorkOrderFile> copyToWorkOrderFile(List<WorkOrderFileDomain> domains, Integer type, String taskWorkOrderId) {
        List<WorkOrderFile> workOrderFileList = new ArrayList<>();
        for (WorkOrderFileDomain fileDomain : domains) {
            WorkOrderFile workOrderFile = new WorkOrderFile();
            BeanUtils.copyProperties(fileDomain, workOrderFile);
            workOrderFile.setFileName(fileDomain.getFileName());
            workOrderFile.setFileUrl(fileDomain.getFileUrl());
            workOrderFile.setId(UUID.randomUUID().toString());
            workOrderFile.setWorkOrderId(taskWorkOrderId);
            workOrderFile.setFileType(type);
            workOrderFile.setDeleteFlag(DataValidity.VALID.getState());
            workOrderFileList.add(workOrderFile);
        }
        return workOrderFileList;
    }

    public List<WorkOrderDomain> findWorkOrderByModuleId(String id) {
        List<TaskWorkOrder> workOrderList = workOrderRepository.findByTaskIdAndDeleteFlagOrderByWorkOrderNo(id, DataValidity.VALID.getState());
        List<WorkOrderDomain> workOrderDomainList = new ArrayList<>();
        for (TaskWorkOrder taskWorkOrder : workOrderList) {
            WorkOrderDomain workOrderDomain = new WorkOrderDomain();
            BeanUtils.copyProperties(taskWorkOrder, workOrderDomain);
            workOrderDomain.setWorkOrderName(workOrderDomain.getWorkOrderName().replace("/^[0-9a-zA-Z_]{7,18}([_\\-]{1}|[ ])/g",""));
            List<ProjectRoleDomain> roleDomainList = new ArrayList<>();
            for (ProjectRole projectRole : taskWorkOrder.getProjectRoleList()) {
                ProjectRoleDomain roleDomain = new ProjectRoleDomain();
                BeanUtils.copyProperties(projectRole, roleDomain);
                roleDomainList.add(roleDomain);
            }
            Integer count = exercisesRepository.countByTaskId(workOrderDomain.getId());
            if (count>0){
                workOrderDomain.setIsExist(true);
            }else {
                workOrderDomain.setIsExist(false);
            }
            workOrderDomain.setProjectRoleDomainList(roleDomainList);
            workOrderDomainList.add(workOrderDomain);
        }
        return workOrderDomainList;
    }

    public WorkOrderDomain findWorkOrder(String id) {
        TaskWorkOrder taskWorkOrder = workOrderRepository.findOne(id);
        WorkOrderDomain workOrderDomain = new WorkOrderDomain();
        BeanUtils.copyProperties(taskWorkOrder, workOrderDomain);
        List<ProjectRoleDomain> roleDomainList = new ArrayList<>();
        List<WorkOrderFile> workOrderFiles = fileService.findWorkOrderFiles(id);
        List<WorkOrderFileDomain> video = new ArrayList<>();
        List<WorkOrderFileDomain> workOrderMaterial = new ArrayList<>();
        List<WorkOrderFileDomain> soundCode = new ArrayList<>();
        List<WorkOrderFileDomain> workStepList = new ArrayList<>();
        for (WorkOrderFile workOrderFile : workOrderFiles) {
            WorkOrderFileDomain domain = new WorkOrderFileDomain();
            BeanUtils.copyProperties(workOrderFile, domain);
            workOrderFile.setDeleteFlag(DataValidity.VALID.getState());
            if (WorkOrderFileType.video.getIntValue().equals(domain.getFileType())) {
                video.add(domain);
            } else if (WorkOrderFileType.material.getIntValue().equals(domain.getFileType())) {
                workOrderMaterial.add(domain);
            } else if (WorkOrderFileType.soundCode.getIntValue().equals(domain.getFileType())){
                soundCode.add(domain);
            }else {
                workStepList.add(domain);
            }
        }
        for (ProjectRole projectRole : taskWorkOrder.getProjectRoleList()) {
            ProjectRoleDomain roleDomain = new ProjectRoleDomain();
            BeanUtils.copyProperties(projectRole, roleDomain);
            roleDomainList.add(roleDomain);
        }
        workOrderDomain.setWorkStepList(workStepList);
        workOrderDomain.setProjectRoleDomainList(roleDomainList);
        workOrderDomain.setSoundCode(soundCode);
        workOrderDomain.setWorkOrderMaterial(workOrderMaterial);
        workOrderDomain.setVideo(video);
        return workOrderDomain;
    }

    public Integer countWorkOrder(String taskId) {
        return workOrderRepository.countByTaskIdAndDeleteFlag(taskId, DataValidity.VALID.getState());
    }

    public Map<String, Object> delete(DeleteDomain deleteDomain) {
        Map<String, Object> result = new HashMap<String, Object>();
        TaskWorkOrder taskWorkOrder = workOrderRepository.findOne(deleteDomain.getId());

        if (Objects.isNull(taskWorkOrder)) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "未查询到工单");
        } else {
            Project project = projectService.findProject(deleteDomain.getProjectId());
            taskWorkOrder.setDeleteFlag(DataValidity.INVALID.getState());
            workOrderRepository.save(taskWorkOrder);
            if (!Objects.isNull(project)) {
                project.setWorkOrderNum(project.getWorkOrderNum()-1);
                projectService.save(project);
            }
            ModuleTask moduleTask = taskRepository.findOne(taskWorkOrder.getTaskId());
            if (!Objects.isNull(moduleTask)) {
                moduleTask.setWorkOrderNum(countWorkOrder(taskWorkOrder.getTaskId()));
                taskRepository.save(moduleTask);
            }
            updateSort(taskWorkOrder.getTaskId());
            result.put(ApiReturnConstants.SUCCESS, true);
            result.put(ApiReturnConstants.DATA, "删除成功");
        }
        return result;
    }

    public void updateSort(String taskId) {
        List<TaskWorkOrder> taskWorkOrderList = workOrderRepository.findByTaskIdAndDeleteFlagOrderByWorkOrderNo(taskId, DataValidity.VALID.getState());

        for (int i = 0; i < taskWorkOrderList.size(); i++) {
            taskWorkOrderList.get(i).setWorkOrderNo(i + 1);
        }
        workOrderRepository.save(taskWorkOrderList);
    }
}
